package controller;
import implementor.SellerInfoImp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import uiframework.UIFrameWork;
import uiframework.Validater;
import utilities.AppUtilites;
import utilities.Browser;
import utilities.Constants;
import utilities.ViewUtilites;
import views.inventory.AddNewSeller;

import daoInterface.SellDao;
import daoInterface.SellerInfoDao;
import dto.SellerInfo;




public class AddNewSellerController extends Browser implements ActionListener,CaretListener
{
	AddNewSeller view;
	SellerInfo model;
	SellerInfoDao sd;
	SellerInfo[] sells;
	
	
	
	
	public AddNewSellerController()
	{
		
	}


	public AddNewSellerController(AddNewSeller view, SellerInfo model) {
		super();
		this.view = view;
		this.model = model;
		view.actionListener(this);
		sd=new SellerInfoImp();
		try {
			sells=sd.retrieveAll();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		maxLength=sells.length;
		index=-1;
		this.makeAutoComplete();
		
		
		
	}


	public AddNewSeller getView() {
		return view;
	}


	public void setView(AddNewSeller view) {
		this.view = view;
	}


	public SellerInfo getModel() {
		return model;
	}


	public void setModel(SellerInfo model) {
		this.model = model;
	}
	public void reactOnSave()
	{
	     fillmodelfromview();
	    
	     Validater validate=new Validater(view);
	     String message=validate.validateForEmpty();
	     
		try
		{
			
			String email=view.gettEmail().getText().trim();
			System.out.println(message);
			if(message.equals("")==true)
			{
				boolean res=Validater.validateEmail(email);
				if(res==true)
				{
				
				sd.add(model);
				JOptionPane.showMessageDialog(null, "Data successfully added");
				}
				else
				{
					JOptionPane.showMessageDialog(null, "Please Enter Email in proper format!!!");
				}
			}
			else 
				
			{
				if(model.getSellerEmail().trim().equals("")==true && model.getSellerName().equals("")!=true && model.getSellerPhone().equals("")!=true
						&& model.getSellerAddress().equals("")!=true)
				{
					
					sd.add(model);
					JOptionPane.showMessageDialog(null, "Data successfully added");
					
				}
				else
				{
					JOptionPane.showMessageDialog(null, "Empty fields not allowed");
				}
			}
		}
		
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Catagory Name already exist, please use another one");
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
		
		}
	}
	
	
	public void reactOnMarkInactive() throws Exception
	{
		String sellerName=view.gettName().getText();
		model=sd.retrieve("sellerName",sellerName);
		
		model.setStatus(Constants.INACTIVE);
		sd.update(model);
		
		
	}
	
	public void reactOnUpdate() throws Exception
	{
		int sellerId=Integer.parseInt(view.getLblSellerid().getText());
	    fillmodelfromview();
	    model.setautoSellerId(sellerId);
		try
		{
			sd.update(model);
			JOptionPane.showMessageDialog(null, "Data successfully Updated.");
		}
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Catagory Name already exist, please use another one");
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully Added,Please try again !");
		}
	}
	
	
	
	public void reactOnSearch() throws Exception
	{
		/*
		 * SHOW ALWAYS IN UPPER CASE
		 */
		String sellername=view.gettName().getText().toLowerCase();
		model=sd.retrieve("sellerName", sellername);
	    this.fillViewFormFromModel();
	    view.getLblSellerid().setText(model.getautoSellerId()+"");
	    System.out.println(model.getautoSellerId()+""+"id");
		
	}
	
	public void reactOnClear()
	{
		Validater val=new Validater(view);
		val.refresh();
	}
	public void reactOnExit()
	{
		
	}
	
	public void fillmodelfromview()
	{
		model=new SellerInfo();
		// Save always in lower case
		model.setSellerName(view.gettName().getText().toLowerCase());
		model.setSellerPhone(view.gettPhone().getText());
		model.setSellerEmail(view.gettEmail().getText());
		model.setSellerAddress(view.getTextAreaAdress().getText());
		model.setStatus(Constants.ACTIVE);
		
	}
	
	
	
	
	
	public void fillViewFormFromModel(){
		// TODO Auto-generated method stub
		
		view.gettName().setText(model.getSellerName());
		view.gettPhone().setText(model.getSellerPhone());
		view.gettEmail().setText(model.getSellerEmail());
		view.getTextAreaAdress().setText(model.getSellerAddress());
		
		
		if(model.getStatus()==1)
		{
			view.getBtnDelete().setText("MARK INACTIVE");
			
		}
		
		if(model.getStatus()==0)
		{
			view.getBtnDelete().setText("MARK ACTIVE");
			
			
		}
		
	}
	
	private void makeAutoComplete()
	{
		List<String> dataName = new ArrayList<String>();
		List<String>dataPhone = new ArrayList<String>();
		for(int i=0;i<sells.length;i++)
		{
			dataName.add(sells[i].getSellerName());
			dataPhone.add(sells[i].getSellerPhone());
		}
		ViewUtilites.makeAutoCompleteJtextbox(view.gettName(),dataName,false);
		ViewUtilites.makeAutoCompleteJtextbox(view.gettPhone(),dataPhone,false);
		
	}
	
	
	
	
	
	@Override
	public void actionPerformed(ActionEvent ar) 
	{
		String k=ar.getActionCommand();
		
		if(k.contains("SAVE"))
		{
			reactOnSave();
		}
		
		if(k.contains("MARK INACTIVE"))
		{
			try {
				reactOnMarkInactive();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("UPDATE"))
		{
			try {
				reactOnUpdate();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("<<"))
		{
			
			try {
				reactOnBack();
				model=sells[index];
				fillViewFormFromModel();
				view.getLblSellerid().setText(model.getautoSellerId()+"");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("SEARCH"))
		{
			try {
				reactOnSearch();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains(">>"))
		{
			try {
				reactOnForward();
				model=sells[index];
				fillViewFormFromModel();
				view.getLblSellerid().setText(model.getautoSellerId()+"");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(k.contains("CLEAR"))
		{
			reactOnClear();
		}
		if(k.contains("EXIT"))
		{
			reactOnExit();
		}
		
	}


	@Override
	public void caretUpdate(CaretEvent e) {
		
		System.out.println("ajay");
		try{
		JTextField textField = (JTextField) e.getSource();
		if(textField == view.gettName())
		{
			String name = textField.getName();
		    for(int i=0;i<this.sells.length;i++)
		    {
		    	System.out.println(sells[i].getSellerName());
		    	if(name.equals(sells[i].getSellerName()))
		    	{
		    		view.getLblSellerid().setText(sells[i].getautoSellerId()+"");
		    		
		    		break;
		    	}
		    }
		}
		if(textField == view.gettPhone())
		{
			String phone = textField.getName();
			
			for(int i=0;i<this.sells.length;i++)
		    {
		    	if(phone.equals(sells[i].getSellerPhone()))
		    	{
		    		view.getLblSellerid().setText(sells[i].getautoSellerId()+"");
		    		break;
		    	}
		    }
		}
		
	}

	
	catch(Exception ex)
	{
		
	}
	
	}
}
